package com.lizemin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lizemin.entity.RespBean;
import com.lizemin.entity.Teacher;
import com.lizemin.mapper.TeacherMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author lzm
 * @date 2025/3/23 12:18
 * @description
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    HttpSession session;

    @Autowired
    private TeacherMapper teacherMapper;

    @GetMapping("/login")
    public RespBean login(String username, String password) {
        if (StringUtils.isAnyBlank(username, password)) {
            return RespBean.fail("用户名或密码不能为空");
        }
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teacher::getName, username)
                .eq(Teacher::getPassword, password);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (Objects.isNull(teacher)) {
            return RespBean.fail("用户名或密码错误");
        }
        log.info("登录成功！");
        session.setAttribute("user", teacher);
        return RespBean.success();
    }

    @GetMapping("/logout")
    public RespBean logout() {
        session.invalidate();
        return RespBean.success();
    }

}
